package com.yuhf.dbutils;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.yuhf.dbutils.exception.DaoException;

public class DBConnection {
	
	private static Logger log=Logger.getLogger(DBConnection.class);
	
	private static final String CLASS_NAME;
	private static final String URL;
	private static final String USERNAME;
	private static final String PASSWORD;
	
	private static ThreadLocal<Connection> connections=new ThreadLocal<>();

	static {
		Properties prop=new Properties();
		try {
			prop.load(DBConnection.class.getResourceAsStream("/jdbc.properties"));
		} catch (IOException e) {
			log.error("jdbc.properties file not found,error message is "+e.getMessage());
			throw new DaoException("jdbc.properties file not found,error message is "+e.getMessage());
		}
		CLASS_NAME=prop.getProperty("jdbc.className");
		URL=prop.getProperty("jdbc.url");
		USERNAME=prop.getProperty("jdbc.userName");
		PASSWORD=prop.getProperty("jdbc.password");
		try {
			Class.forName(CLASS_NAME);
		} catch (ClassNotFoundException e) {
			log.error("class file not found,error message is "+e.getMessage());
			throw new DaoException("class file not found,error message is "+e.getMessage());
		}
	}
	
	public static Connection getConnection() {
		Connection connection=connections.get();
			try {
				if(null==connection||connection.isClosed()) {
					connection=DriverManager.getConnection(URL,USERNAME,PASSWORD);
				}
			} catch (SQLException e) {
				log.error("connection database error,error message is "+e.getMessage());
				throw new DaoException("connection database error,error message is "+e.getMessage());
			}
			connections.set(connection);
		return connection;
	}
	
	public static void closeConnection(Connection connection) {
		try {
			if(null!=connection && !connection.isClosed()) {
				connection.close();
			}
		} catch (SQLException e) {
			log.error(e.getMessage());
			throw new DaoException(e.getMessage());
		}
	}
}
